import { Component, OnInit } from '@angular/core';
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
import { FileImportHttpService } from '../services/file-import.service';

@Component({
  selector: 'app-file-fragment',
  templateUrl: './file-fragment.component.html',
  styleUrls: ['./file-fragment.component.less']
})
export class FileFragmentComponent implements OnInit{
    uploading = false;
    fileList: UploadFile[] = [];

    constructor(
        private msg: NzMessageService,
        private http: FileImportHttpService,
        private modalService: NzModalService
    ) {}

    ngOnInit() {}

    beforeUpload = (file: UploadFile): boolean => {
        // 检查是否已经有文件在列表中
        if (this.fileList.length > 0) {
            this.msg.error('每次只能上传一个文件！');
            return false;
        }

        // 检查文件类型是否为.csv
        const isCSV =
            file.type === 'text/csv' ||
            file.name.slice(-4).toLowerCase() === '.csv';
        if (!isCSV) {
            this.msg.error('只能上传CSV文件！');
            return false;
        }

        // 检查文件大小是否超过30MB
        const isLt30M = file.size / 1024 / 1024 < 30;
        if (!isLt30M) {
            this.msg.error('文件必须小于30MB！');
            return false;
        }

        this.fileList = this.fileList.concat(file);
        return false;
    };

    handleUpload(): void {
        if (this.fileList.length === 0) {
            this.msg.error('请先选择文件');
            return;
        }
        const file = this.fileList[0];
        const chunkSize = 1024 * 1024; // 1MB
        const totalChunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        this.uploading = true;

        const uploadChunk = () => {
            const start = currentChunk * chunkSize;
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);
            const formData = new FormData();
            formData.append('file', chunk);
            formData.append('fileName', file.name);
            formData.append('chunkIndex', currentChunk.toString());
            formData.append('totalChunks', totalChunks.toString());

            this.http.uploadFragment(formData).subscribe(
                (res) => {
                    if (res.status === 200) {
                        currentChunk++;
                        if (currentChunk < totalChunks) {
                            uploadChunk();
                        } else {
                            this.msg.success('文件上传完成');
                            this.uploading = false;
                            // 开发中的项目从这里开始进行导入解析入库，如果遇到报错就下载错误详情文件，但是我们这里就不进行下一步了
                            // this.getImportResult({ key: res.data });
                        }
                    } else {
                        this.uploading = false;
                        this.msg.error(res.msg || '上传失败');
                    }
                },
                (error) => {
                    this.uploading = false;
                    this.msg.error('上传失败');
                }
            );
        };

        uploadChunk();
    }

    getImportResult(data: any): void {
        this.http.getImportResult(data).subscribe((res) => {
            console.log(92, res);
            if (res.status === 200) {
                this.msg.success(res.msg.message);
                this.uploading = false;
            } else {
                this.uploading = false;
                this.msg.error(res.msg.message);
                this.modalService.confirm({
                    nzTitle: '是否下载错误详情文件?',
                    // nzContent: '<b style="color: red;">Some descriptions</b>',
                    nzOkText: '下载错误文件',
                    // nzOkType: 'danger',
                    nzOnOk: () =>  this.downloadErrorFile(res.msg.error_file),
                    nzCancelText: '取消',
                    nzOnCancel: () => console.log('Cancel')
                });
                // this.downloadErrorFile(res.msg.error_file);
            }
        });
    }

    private downloadErrorFile(filePath: string): void {
        const url = `/logcollect/api/v1/analysis_result_view/result_download_txt?file_path=${filePath}`;
        fetch(url)
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filePath || '错误结果.txt';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url); // 清理URL对象
            })
            .catch(error => {
                this.msg.error('下载文件失败');
                console.error('下载文件失败:', error);
            });
    }
}
